package com.cjm.pattern.adapter.vonewihnopattern;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class LogFileOperate implements LogFileOperateApi {
    public static void main(String[] args) {
        LogModel l1 = new LogModel();
        l1.setContent("content");
        l1.setLogId("1");
        l1.setOperatorUser("cjm");
        l1.setOperatorTime("2021");

        List<LogModel> list = new ArrayList<>();
        list.add(l1);

        LogFileOperateApi logFileOperateApi = new LogFileOperate("D:\\tmp\\AdapterLog.log");
        logFileOperateApi.writeLogFile(list);

        List<LogModel> logModels = logFileOperateApi.readLogFile();
        System.err.println(logModels.get(0));
    }
    private String logFilePathName = "D:\\tmp\\AdapterLog.log";

    public LogFileOperate(String logFilePathName) {
        if (logFilePathName != null && logFilePathName.trim().length() > 0) {
            this.logFilePathName = logFilePathName;
        }
    }

    @Override
    public List<LogModel> readLogFile() {
        List<LogModel> list = new ArrayList<>();
        File f = new File(logFilePathName);
        if (f.exists()) {
            try (ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)))){
                list = (List<LogModel>) oin.readObject();
                if (list == null || list.size() < 1) {
                    list = new ArrayList<>();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public void writeLogFile(List<LogModel> list) {
        File f = new File(logFilePathName);
        try (ObjectOutputStream oout = new ObjectOutputStream((new BufferedOutputStream(new FileOutputStream(f))))){
            oout.writeObject(list);
        } catch (IOException e) {
        }

    }
}
